<template>
  <div class="chat-box" :style="{
    top: `${position.y}px`,
    left: `${position.x}px`,
    transform: `scale(${scale})`,
    transformOrigin: 'top left'
  }" @mousedown="startDrag" @touchstart.passive="startDrag" @wheel.prevent="handleWheel">
    <div class="header">
      {{ targetUserName }}
      <button class="close-btn" @click="$emit('close')">
        <span class="close-icon">×</span>
      </button>
    </div>
    <div class="message-list" ref="messageList">
      <div v-for="msg in messages" :key="msg.id"
        :class="['message-item', msg.senderId === currentUserId ? 'self' : 'other']">
        {{ msg.content }}
      </div>
    </div>
    <div class="input-area">
      <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="输入消息...">
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useUserStore } from '/@/store';
import SockJS from 'sockjs-client';
import { Stomp } from '@stomp/stompjs';
import axios from 'axios';
import dayjs from 'dayjs';
const router = useRouter();

const handleClose = () => {

    router.push({ name: 'ChatList' }); // 返回聊天列表
  
};

const formatDate = (timestamp?: string) => {
  if (!timestamp) return '';
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm');
};

// 响应式数据
const position = reactive({ x: 1060, y: 70 })
const isDragging = ref(false)
const startOffset = reactive({ x: 0, y: 0 })
const scale = ref(1) // 默认缩放


// 窗口尺寸（用于边界计算）
const windowSize = reactive({
  width: 400, // 原始宽度
  height: 600 // 原始高度
})

// 拖动逻辑
const startDrag = (e) => {
  isDragging.value = true
  const clientX = e.clientX || e.touches[0].clientX
  const clientY = e.clientY || e.touches[0].clientY

  startOffset.x = clientX - position.x
  startOffset.y = clientY - position.y

  // 添加事件监听
  window.addEventListener('mousemove', handleDrag)
  window.addEventListener('touchmove', handleDrag)
  window.addEventListener('mouseup', stopDrag)
  window.addEventListener('touchend', stopDrag)
}

const handleDrag = (e) => {
  if (!isDragging.value) return

  const clientX = e.clientX || e.touches[0].clientX
  const clientY = e.clientY || e.touches[0].clientY

  // 计算边界限制
  const maxX = window.innerWidth - windowSize.width * scale.value
  const maxY = window.innerHeight - windowSize.height * scale.value

  position.x = Math.min(maxX, Math.max(0, clientX - startOffset.x))
  position.y = Math.min(maxY, Math.max(0, clientY - startOffset.y))
}

const stopDrag = () => {
  isDragging.value = false
  window.removeEventListener('mousemove', handleDrag)
  window.removeEventListener('touchmove', handleDrag)
  window.removeEventListener('mouseup', stopDrag)
  window.removeEventListener('touchend', stopDrag)
}

// 缩放逻辑
const handleWheel = (e) => {
  const delta = e.deltaY > 0 ? -0.1 : 0.1
  const newScale = Math.min(2, Math.max(0.8, scale.value + delta))

  // 调整位置保持居中
  const rect = e.target.getBoundingClientRect()
  const centerX = (e.clientX - rect.left) / scale.value
  const centerY = (e.clientY - rect.top) / scale.value

  scale.value = newScale

  // 更新位置
  position.x = e.clientX - centerX * newScale
  position.y = e.clientY - centerY * newScale
}



// 定义消息类型
interface Message {
  id?: number;
  senderId: string;
  receiverId: string;
  content: string;
  createTime?: Date;
}

// 定义props类型
const props = defineProps<{
  targetUserId: string;
  targetUserName: string;
  show: boolean;
}>();




// 响应式变量
const newMessage = ref('');
const messages = ref<Message[]>([]);
let stompClient: any = null;
let reconnectCount = 0; // 重连计数器

// 从Vuex获取当前用户ID
const userStore = useUserStore();
const currentUserId = computed(() => userStore.user_id || '');

// 初始化 STOMP 客户端
const initializeStompClient = () => {
  const socket = new SockJS('http://localhost:8080/api/ws');
  stompClient = Stomp.over(socket);
  stompClient.connect({},
    () => {
      console.log('连接成功');
      stompClient.subscribe(`/user/${currentUserId.value}/queue/messages`, onMessageReceived);
    },
    (error) => {
      console.error('连接失败:', error);
      reconnect(); // 触发重连
    }
  );
};

const message = {
  senderId: currentUserId.value, // 必须与后端实体字段一致
  receiverId: props.targetUserId,
  content: newMessage.value
};

// 消息接收处理
const onMessageReceived = (message: any) => {
  const newMsg: Message = JSON.parse(message.body);
  messages.value.push(newMsg);
};

// 重连逻辑
const reconnect = () => {
  if (reconnectCount < 5) { // 限制最大重连次数
    setTimeout(() => {
      initializeStompClient();
      reconnectCount++;
    }, 2000);
  }
};

// 发送消息
const sendMessage = () => {
  if (!stompClient || !stompClient.connected) return;
  if (!newMessage.value.trim()) return;

  const message: Message = {
    senderId: currentUserId.value,
    receiverId: props.targetUserId,
    content: newMessage.value,
  };

  stompClient.send("/app/chat", {}, JSON.stringify(message));
  messages.value.push(message); // 乐观更新
  newMessage.value = '';
};

// 加载历史消息
const loadHistoryMessages = () => {
  axios.get('http://localhost:8080/api/messages', {
    params: {
      currentUserId: currentUserId.value,
      targetUserId: props.targetUserId,
    }
  }).then(res => {
    messages.value = res.data;
  });
};

// 组件挂载时初始化
onMounted(() => {
  initializeStompClient();
  loadHistoryMessages();
});

// 组件卸载时清理
onBeforeUnmount(() => {
  if (stompClient?.connected) {
    stompClient.disconnect();
  }
});
</script>

<style scoped lang="less">
.chat-box {
  position: fixed;
  width: 400px;
  height: 600px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  transition:
    transform 0.3s ease,
    top 0.2s ease,
    left 0.2s ease;
  touch-action: none;
  /* 禁用默认触摸行为 */

  @keyframes slideIn {
    from {
      transform: translateY(100%);
    }

    to {
      transform: translateY(0);
    }
  }
}

.header {
  padding: 16px;
  background: #409eff;
  color: white;
  border-radius: 16px 16px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  user-select: none;
}

.close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  color: white;
  font-size: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.close-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 24px;
  line-height: 1;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: rotate(90deg) scale(1.1);
}

.close-btn:active {
  transform: rotate(90deg) scale(0.9);
}

.message-list {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #f9f9f9;
}

.message-item {
  margin-bottom: 12px;
  padding: 12px 16px;
  border-radius: 16px;
  max-width: 75%;
}

.message-item.self {
  background: #409eff;
  color: white;
  margin-left: auto;
  border-radius: 16px 4px 16px 16px;
}

.message-item.other {
  background: #f5f5f5;
  margin-right: auto;
  border-radius: 4px 16px 16px 16px;
}

.input-area {
  display: flex;
  gap: 8px;
  padding: 16px;
  background: #f5f5f5;
  border-top: 1px solid #eee;
}

.input-area input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  font-size: 15px;
  transition: all 0.3s ease;
}

.input-area input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  outline: none;
}

.input-area button {
  padding: 12px 24px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.input-area button:hover {
  background: #66b1ff;
}

@media (max-width: 768px) {
  .chat-box {
    width: 100%;
    height: 100%;
    max-height: 80vh;
    border-radius: 0;
    bottom: 0;
    right: 0;
    animation: none;
  }

  .message-list {
    padding: 8px;
  }

}
</style>